﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp_Event
{
    /// <summary>
    /// CustomEventWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CustomEventWindow : Window
    {
        public CustomEventWindow()
        {
            InitializeComponent();
        }

        private void ChlidClass_Tap(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("--------ChlidClass_Tap---------");
        }

        private void ParentClass_Tap(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("--------ParentClass_Tap---------");
        }

        private void ParentClass_PreviewTap(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("--------ParentClass_PreviewTap---------");
        }

        private void ChlidClass_PreviewTap(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("--------ChlidClass_PreviewTap---------");
        }
    }

    public class BaseEventClass : ContentControl
    {
        //冒泡事件
        protected static readonly RoutedEvent TapEvent = 
            EventManager.RegisterRoutedEvent("Tap",RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(BaseEventClass));

        public event RoutedEventHandler Tap
        { 
            add => AddHandler(TapEvent, value);
            remove => RemoveHandler(TapEvent, value);
        }

        //隧道事件
        protected static readonly RoutedEvent PreviewTapEvent =
            EventManager.RegisterRoutedEvent("PreviewTap", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(BaseEventClass));

        public event RoutedEventHandler PreviewTap
        {
            add => AddHandler(TapEvent, value);
            remove => RemoveHandler(TapEvent, value);
        }
    }

    public class ParentClass : BaseEventClass
    { 
        
    }

    public class ChlidClass : BaseEventClass 
    {
        public ChlidClass()
        {
            Task.Run(async () => 
            {
                await Task.Delay(2000);
                this.Dispatcher.Invoke(new Action(() => 
                {
                    this.RaiseEvent(new RoutedEventArgs(PreviewTapEvent, this));
                    this.RaiseEvent(new RoutedEventArgs(TapEvent, this));
                }));
            });
            
        }
    }
}
